'use client';

import {
  MouseEventHandler,
  SVGProps,
  useEffect,
  useMemo,
  useRef,
  useState,
} from 'react';
import './CategoriesMenu.scss';
import { Box } from '@mui/material';
import { getCategories, getProducts } from '@/services';
import { useActions, useGlobalState } from '@/hooks';
import Link from 'next/link';
import { NextPage } from 'next';
import {
  KeyboardArrowDownRounded as IconArrowDown,
  KeyboardArrowRightRounded as IconArrowRight,
} from '@mui/icons-material';
import FontIcon from '../FontIcon';

const rootId = Number(process.env.NEXT_PUBLIC_ROOT_CATEGORY_ID);

const getCategoryLink = (cat: Obj, categories: any[] | null) => {
  let currCat = { ...cat };
  if (!currCat.url_key) return '';
  const pathArray = [currCat.url_key];
  while (currCat?.parent_id && currCat?.parent_id != rootId) {
    currCat = categories?.find(c => c.category_id == currCat.parent_id);
    if (currCat) pathArray.push(currCat.url_key);
  }
  return '/categories/' + pathArray.reverse().join('/');
};

const SecondCategoryCard = ({
  category,
  childrens,
  categories,
  overId,
  onOver,
}: {
  category: any;
  childrens?: any[] | null;
  categories: any[] | null;
  overId?: string;
  onOver?: MouseEventHandler;
}) => {
  const cardRef = useRef<any>(null);
  useEffect(() => {
    if (cardRef.current) {
      const rows = Math.ceil(cardRef.current?.clientHeight / 5) + 2;
      cardRef.current.style.gridRowEnd = `span ${rows}`;
    }
  }, [cardRef, childrens]);
  return (
    <Box className="category-block" ref={cardRef}>
      <div
        onMouseOver={onOver}
        data-category_id={category.category_id}
        data-parent_id={category.parent_id}
        data-title={category.title}
        className={
          'category-item ' + (overId == category.category_id && 'active')
        }
      >
        <Link href={getCategoryLink(category, categories)}>
          {category.title}
        </Link>
      </div>
      {childrens?.map((ca3: any, index) => (
        <div
          key={index}
          onMouseOver={onOver}
          data-category_id={ca3.category_id}
          data-parent_id={ca3.parent_id}
          data-title={ca3.title}
          className={
            'category-item sub ' + (overId == ca3.category_id && 'active')
          }
        >
          <Link href={getCategoryLink(ca3, categories)}>{ca3.title}</Link>
        </div>
      ))}
    </Box>
  );
};

// type Props = {
//   serverData: Obj;
// };
// const CategoriesMenu: NextPage<Props> = ({ serverData }) => {
const CategoriesMenu: NextPage = () => {
  const categories = useGlobalState('product', 'categoryList');

  const categoriesLv1 = useMemo(() => {
    const lv1_list = categories.filter((d: any) => d.parent_id == rootId);
    return lv1_list;
  }, [categories]);

  const [hoverCategory1, seHoverCategory1] = useState<any>(null);
  const [hoverCategory2, seHoverCategory2] = useState<any>(null);
  const [viewMenu, setViewMenu] = useState<any>(false);
  const [viewMenuSub, setViewMenuSub] = useState<any>(false);

  const handleItemOver = (e: any) => {
    if (e.currentTarget?.dataset?.category_id) {
      const cat = e.currentTarget?.dataset;
      seHoverCategory1({ ...cat });
      setViewMenuSub(true);
    }
  };
  const handleItemOver2 = (e: any) => {
    if (e.currentTarget?.dataset?.category_id) {
      const cat = e.currentTarget?.dataset;
      seHoverCategory2({ ...cat });
    }
  };
  const handleMouseButtonEnter = (e: any) => {
    e.stopPropagation();
    setViewMenu(true);
    setViewMenuSub(false);
    // setOverCategoryId1(null)
    seHoverCategory1(null);
  };
  const handleMouseButtonLeave = () => {
    setViewMenu(false);
  };
  const handleMouseMenuEnter = (e: any) => {
    e.stopPropagation();
    setViewMenu(true);
    // setOverCategoryId2(null)
    seHoverCategory2(null);
  };
  const handleMouseMenuLeave = () => {
    setViewMenu(false);
    setViewMenuSub(false);
  };
  const handleMouseSubEnter = (e: any) => {
    e.stopPropagation();
    setViewMenuSub(true);
  };
  const handleMouseSubLeave = () => {
    setViewMenuSub(false);
  };
  const getChildrens = (pid: any) => {
    if (!pid) return null;
    return categories.filter((d: any) => d.parent_id == pid);
  };

  function adjustGridHeight() {
    const gridItems = document.querySelectorAll('.category-block');
    const itemHeights = Array.from(gridItems).map(
      (item: any) => item.offsetHeight
    );
    const maxHeight = Math.max(...itemHeights);
    document.documentElement.style.setProperty(
      '--grid-auto-rows',
      `${maxHeight}px`
    );
  }
  useEffect(() => {
    adjustGridHeight();
    //fix content can't display on some version chrome
    hoverCategory1?.category_id
      ? setTimeout(() => {
          document
            .querySelector('.main-menu-category-level-2-wrapper')
            ?.setAttribute('style', 'height: 100%;');
        }, 10)
      : document
          .querySelector('.main-menu-category-level-2-wrapper')
          ?.setAttribute('style', 'height: 99.9%;');
  }, [hoverCategory1]);

  useEffect(() => {
    const element = document.querySelector('.main-menu-category-level-1-list');
    if (element && categoriesLv1?.length) {
      const style = window.getComputedStyle(element);
      const lv1_height = element?.clientHeight + parseInt(style.marginTop);
      lv1_height &&
        document
          .querySelector('.main-menu-category-level-1')
          ?.setAttribute('style', 'height: ' + lv1_height + 'px;');
      console.log('🟢🟢🟢Categories Menu init ', lv1_height);
    }
  }, [categoriesLv1]);

  return (
    <div className="main-menu-category-wrapper">
      <button
        className="main-menu-category-button"
        onMouseEnter={handleMouseButtonEnter}
        onMouseLeave={handleMouseButtonLeave}
      >
        Categories
        <FontIcon
          className={
            'main-menu-category-button-arrow ' +
            (viewMenu || viewMenuSub ? 'arrow-up' : 'arrow-down')
          }
          style={{ width: '18px', height: '18px' }}
          name="expand-line"
        />
      </button>
      <div className="main-menu-category-dropdown">
        <div
          className={
            'main-menu-category-level-1 ' +
            (viewMenu || viewMenuSub ? 'show-list' : 'hide-list')
          }
          onMouseEnter={handleMouseMenuEnter}
          onMouseLeave={handleMouseMenuLeave}
        >
          <div className="main-menu-category-level-1-list">
            {categoriesLv1.map((ca: any, index: number) => (
              <li
                key={index}
                onMouseOver={handleItemOver}
                data-category_id={ca.category_id}
                data-parent_id={ca.parent_id}
                data-title={ca.title}
                data-format_title={ca.format_title}
                className={
                  'category-item ' +
                  (hoverCategory1?.category_id == ca.category_id
                    ? 'active'
                    : '')
                }
              >
                <Link href={getCategoryLink(ca, categories)}>
                  {ca.title}
                  {hoverCategory1?.category_id == ca.category_id && (
                    <FontIcon
                      name="forward-line"
                      style={{ width: '18px', height: '18px' }}
                    />
                  )}
                </Link>
              </li>
            ))}
          </div>
        </div>
        <div
          className={
            'main-menu-category-level-2 ' +
            (viewMenuSub ? 'show-list' : 'hide-list')
          }
          onMouseEnter={handleMouseSubEnter}
          onMouseLeave={handleMouseSubLeave}
        >
          <div className="main-menu-category-level-2-wrapper">
            <div
              className="main-menu-category-level2-all"
              data-category_id={hoverCategory1?.category_id}
              data-parent_id={hoverCategory1?.parent_id}
              data-title={hoverCategory1?.title}
            >
              <Link href={getCategoryLink(hoverCategory1, categories)}>
                Shop All {hoverCategory1?.title}
              </Link>
            </div>
            <div className="main-menu-category-level-2-list">
              {getChildrens(hoverCategory1?.category_id)?.map(
                (ca2: any, index: number) => (
                  <SecondCategoryCard
                    key={index}
                    category={ca2}
                    categories={categories}
                    childrens={getChildrens(ca2.category_id)}
                    overId={hoverCategory2?.category_id}
                    onOver={handleItemOver2}
                  />
                )
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default CategoriesMenu;
